﻿using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Tenancy.Helper;
using WebUI;
using System.Data;
using SQLServer.DBUtility;

namespace Tenancy.Server
{
    /// <summary>
    /// Hbung_NeedAndSu 的摘要说明
    /// </summary>
    public class Hbung_NeedAndSu : IHttpHandler
    {
        /// <summary>
        /// 用户发布求租出租接口
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //手机号
            string HBLoginName = context.Request.Params["Tel"];
            string Hbung_Phone = string.Empty;
            if (string.IsNullOrEmpty(HBLoginName))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Tel为空"));
            }
            else
            {
                Hbung_Phone = DESEncrypt.MD5Decrypt(Regex.Replace(HBLoginName.Trim(), @"\s", "+"));
                string pattern = "^1[0-9]{10}$"; //正则表达式字符串
                Regex cgsregex = new Regex(pattern);
                bool isMatch = cgsregex.IsMatch(Hbung_Phone);
                if (!isMatch)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel格式不正确"));
                    return;
                }
            }
            //签名
            string HBsign = context.Request.Params["Sign"];
            if (string.IsNullOrEmpty(HBsign))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Sign为空"));
                return;
            }
            else
            {
                if (GenerClass.IsOkMatch(Hbung_Phone) != Regex.Replace(HBsign, @"\s", "+"))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Sign不匹配"));
                    return;
                }
            }

            //用户id
            string HBuserid = context.Request.Params["UID"];
            int HB_Uid = 0; 
            if(string.IsNullOrEmpty(HBuserid))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("UID为空"));
                return;
            }
            
            else
            {
                if (!int.TryParse(HBuserid, out HB_Uid) || HB_Uid<0)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("UID格式不正确"));
                    return;
                }
                string Ustr = string.Format("select * from Hbung_CompanyInfo where ID='{0}'", HB_Uid);
                DataTable HB_UserData = DbLocalSQL.Query(Ustr).Tables[0];
                if(HB_UserData==null||HB_UserData.Rows.Count==0)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("用户不存在"));
                    return;
                }
            }
            //0是求租，1是出租
            string HbRentType = context.Request.Params["RentType"];
            if(string.IsNullOrEmpty(HbRentType))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("RentType不能为空"));
                return;
            }
            else
            {
                if (HbRentType != "0" && HbRentType!="1")
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("RentType值不正确"));
                    return;
                }
            }
            //0是工程机械，1是高空车
            string HBCarType = context.Request.Params["CarType"];
            if(string.IsNullOrEmpty(HBCarType))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("HBCarType不能为空"));
                return;
            }
            else
            {
                if (HBCarType != "0" && HBCarType != "1")
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("HBCarType值不正确"));
                    return;
                }
            }
            //每天的价格
            string HBPrice = context.Request.Params["Price"];
            int Hb_EveryPrice = 0;
            if (string.IsNullOrEmpty(HBPrice))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Price不能为空"));
                return;
            }
            else
            {
                if(!int.TryParse(HBPrice,out Hb_EveryPrice) || Hb_EveryPrice<0)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Price格式不正确"));
                    return;
                }
            }
            //当前的小时数
            string HB_WorkHours = context.Request.Params["Hours"];
            decimal Whours = 0m;
            if(string.IsNullOrEmpty(HB_WorkHours))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Hours不能为空"));
                return;
            }
            else
            {
                if(!decimal.TryParse(HB_WorkHours,out Whours))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Hours格式不对"));
                    return;
                }
            }
            //开始日期
            string HBStartDate = context.Request.Params["StartDate"];
            DateTime SDate = DateTime.Now;
            if(string.IsNullOrEmpty(HBStartDate))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("StartDate不能为空"));
                return;
            }
            else
            {
                if(!DateTime.TryParse(HBStartDate,out SDate))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("StartDate格式不对"));
                    return;
                }
            }

            //结束日期
            string HBEndDate = context.Request.Params["EndDate"];
            DateTime Edate = DateTime.Now;
            if (string.IsNullOrEmpty(HBEndDate))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("EndDate不能为空"));
                return;
            }
            else
            {
                if(!DateTime.TryParse(HBEndDate,out Edate))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("EndDate格式不对"));
                    return;
                }
            }
            //设备品牌型号
            string HBEquipmentVersion = context.Request.Params["EqNum"];
            if(string.IsNullOrEmpty(HBEquipmentVersion))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("EqNum为空"));
                return;
            }
            else
            {
                if(HBEquipmentVersion.Length>50)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("EqNum长度过长"));
                    return;
                }
            }
            //出厂日期
            string HBLeaveFacDate = context.Request.Params["LeaveDate"];
            DateTime LDate = DateTime.Now;
            if (string.IsNullOrEmpty(HBLeaveFacDate))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("LeaveDate为空"));
                return;
            }
            else
            {
                if(!DateTime.TryParse(HBLeaveFacDate,out LDate))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("LeaveDate格式不对"));
                    return;
                }
            }
            //联系人
            string HBName = context.Request.Params["Name"];
            if(string.IsNullOrEmpty(HBName))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Name为空"));
                return;
            }
            else
            {
                if(HBName.Length>40)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Name长度过长"));
                    return;
                }
            }
            //联系电话
            string HB_cgsTel = context.Request.Params["Telphone"];
            if (string.IsNullOrEmpty(HB_cgsTel))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Telphone为空"));
                return;
            }
            else
            {
                string pattern = "^1[0-9]{10}$"; //正则表达式字符串
                Regex cgsregex = new Regex(pattern);
                bool isMatch = cgsregex.IsMatch(HB_cgsTel);
                if (!isMatch)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Telphone格式不对"));
                    return;
                }
            }
            string NeedSuStr = string.Format(@"insert into Hbung_NeedAndSupply (UID,RentType,CarType,Price,StartDate,EndDate,EquipmentVersion,LeaveFacDate,Name,Telphone,WorkHours) 
              values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}');select @@IDENTITY 
                ", HB_Uid, HbRentType, HBCarType, Hb_EveryPrice, SDate, Edate, HBEquipmentVersion, LDate, HBName, HB_cgsTel, Whours); 
            //图片数据流
            string img = "";//过程图片

            #region 上传头像
            if (HttpContext.Current.Request.Files["PicIO"] != null)
            {
                string[] img_guocheng_names = HttpContext.Current.Request.Files.AllKeys;
                for (int i = 0; i < img_guocheng_names.Length; i++)
                {
                    if (img_guocheng_names[i] == "PicIO")
                    {
                        //需要上传的图片
                        HttpPostedFile _upfile = HttpContext.Current.Request.Files[i];
                        if (_upfile.ContentLength > 0)
                        {
                            PicUload upFiles = new PicUload();
                            string msg = upFiles.fileSaveAs(_upfile);
                            Dictionary<string, string> dic_msg = new Dictionary<string, string>();
                            dic_msg = JsonHelper.JSONToObject<Dictionary<string, string>>(msg);
                            if (dic_msg["status"] == "1")
                            {
                                img += dic_msg["path"] + ",";
                            }
                        }
                    }
                }
                if (img.EndsWith(","))
                {
                    img = img.Remove(img.Length - 1, 1);
                    
                }
                string PicStr = string.Format(@"insert into Hbung_Pic (NID,PicPath,AddDate,RentType,CarType)
                           values (4,'{0}',getdate(),'{0}','{1}')
                           ", img, HbRentType,HBCarType);

                List<string> Strs = new List<string>();
                Strs.Add(NeedSuStr);
                Strs.Add(PicStr);
                if (DBHelpSQL.ExecuteSqlTran(Strs) > 0)
                {
                    context.Response.Write(GenerClass.SetSucessJsData("发布成功", "[]"));
                    return;
                }
                else
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("发布失败"));
                    return;
                }
            }
           
            #endregion

            if (DBHelpSQL.ExecuteSql(NeedSuStr) > 0)
            {
                context.Response.Write(GenerClass.SetSucessJsData("发布成功", "[]"));
            }
            else
            {
                context.Response.Write(GenerClass.SetChangeErrorJsData("发布失败"));
                return;
            }

                
               

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}